package best.driver.android.View.photocrop;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import best.driver.android.Event.UploadFileEvent;
import best.driver.android.Utils.FileImageUpload;
import best.driver.android.Utils.Util;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import de.greenrobot.event.EventBus;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

public class PhotoBase extends BasePhotoCropActivity implements CropHandler{

    public final static int IMAGE_FROM_CAMERA = 101;

    public final static int IMAGE_FROM_PHOTO = 102;

    private Uri imageFilePath;

    private ImageView targetImageView;

    private TextView mTvHint;

    private TextView mTvDesc;

    protected DisplayImageOptions options;

    public CropParams mCropParams = new CropParams();

    private int mType;

    private Bitmap mBitmap;

    public String mFileId;


    public void gotoSelectPhoto(ImageView imageView, final int type) {
        targetImageView = imageView;
        final SelectPhotoDialog mSelectPhotoDialog = new SelectPhotoDialog(
                getActivity(), type);
        if(type >= 0 && type <= 5) {
            mSelectPhotoDialog.setAlbumVisible();
        }
        mSelectPhotoDialog
                .setListener(new SelectPhotoDialog.SelectPhotoListener() {
                    @Override
                    public void cancelSelect() {
                    }

                    @Override
                    public void selectTakePhoto() {
                        startTakePhoto(type);
                        mType = type;
                    }

                    @Override
                    public void selectFromAlbum() {
                        startSelectPhotoFromAlbum(type);
                        mType = type;
                    }
                });
    }

    public void gotoSelectPhoto(ImageView imageView, TextView tvHint, TextView tvDesc, final int type) {
        targetImageView = imageView;
        mTvHint = tvHint;
        mTvDesc = tvDesc;
        final SelectPhotoDialog mSelectPhotoDialog = new SelectPhotoDialog(
                getActivity(), type);
        if(type >= 0 && type <= 5) {
            mSelectPhotoDialog.setAlbumVisible();
        }
        mSelectPhotoDialog
                .setListener(new SelectPhotoDialog.SelectPhotoListener() {
                    @Override
                    public void cancelSelect() {
                    }

                    @Override
                    public void selectTakePhoto() {
                        startTakePhoto(type);
                        mType = type;
                    }

                    @Override
                    public void selectFromAlbum() {
                        startSelectPhotoFromAlbum(type);
                        mType = type;
                    }
                });
    }

    public void startTakePhoto(int type) {
//        Intent intent = CropHelper.buildCaptureIntent(mCropParams.uri);
//        startActivityForResult(intent, CropHelper.REQUEST_CAMERA);
        startTakeUnCropPhoto(type);
    }

    public void startSelectPhotoFromAlbum(int type) {
        //startActivityForResult(CropHelper.buildCropFromGalleryIntent(mCropParams), CropHelper.REQUEST_CROP);
        Intent picture = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(picture, IMAGE_FROM_PHOTO);
    }

    public void reqUploadPhoto(Bitmap image, final int type) {
        showWaiting();
        if (image == null) {
            return;
        }
    }

    public void startTakeUnCropPhoto(int type) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        startActivityForResult(intent, IMAGE_FROM_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == IMAGE_FROM_CAMERA) {
            Bundle extras = data.getExtras();
            if(extras != null) {
                Bitmap bitmap = (Bitmap) extras.get("data");
                if (bitmap != null) {
                    onGetBitmap(bitmap);
                }
            }
        } else if(requestCode == IMAGE_FROM_PHOTO) {
            Uri uri = data.getData();
            if(uri != null) {
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                    if(bitmap != null) {
                        onGetBitmap(bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    protected void onGetBitmap(final Bitmap bitmap) {
        try {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            // 设置想要的大小
            int newWidth = 640;
            int newHeight = 640;
            // 计算缩放比例
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            float scale = scaleHeight > scaleWidth ? scaleWidth : scaleHeight;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scale, scale);
            // 得到新的图片
            final Bitmap newbm = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,
                    true);
            mBitmap = newbm;
            //FileImageUpload.saveBitmap2file(bitmap);
            UploadFileTask task = new UploadFileTask(getContext(),bitmap, mType, mUploadListener);
            task.execute(Environment.getExternalStorageDirectory()+FileImageUpload.FILE_PATH);
            //task.execute(newbm);
            //task.execute(FileImageUpload.saveBitmap2file(newbm));
        } catch (Exception e) {

        }
    }


    protected void onUploadSuccess(int type) {

    }

    protected void onUploadFailed() {

    }

    @Override
    public CropParams getCropParams() {
        return mCropParams;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    public void onPhotoCropped(Uri uri) {
        //Log.d(TAG, "Crop Uri in path: " + uri.getPath());
        //Toast.makeText(this, "Photo cropped!", Toast.LENGTH_LONG).show();
        //mImageView.setImageBitmap(CropHelper.decodeUriAsBitmap(this, mCropParams.uri));
        mBitmap = CropHelper.decodeUriAsBitmap(this, uri);
        if (mBitmap != null) {
            //targetImageView.setImageBitmap(Util.convertHeadPicture(bitmap));
            //targetImageView.setImageBitmap(bitmap);
            //targetImageView.setTag(bitmap);
            onGetBitmap(mBitmap);
        }
    }

    @Override
    public void onCropCancel() {
        //Toast.makeText(this, "Crop canceled!", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onCropFailed(String message) {
        //Toast.makeText(this, "Crop failed:" + message, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getCropParams() != null)
            CropHelper.clearCachedCropFile(getCropParams().uri);
    }

    private UploadListener mUploadListener = new UploadListener() {
        @Override
        public void uploadSuccess(final String fileId) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mFileId = fileId;

                    if (mBitmap != null) {
                        //targetImageView.setImageBitmap(Util.convertHeadPicture(bitmap));
                        targetImageView.setImageBitmap(mBitmap);
                        targetImageView.setTag(mBitmap);
                        if(mTvHint != null) {
                            mTvHint.setVisibility(View.GONE);
                        }
                        if(mTvDesc != null) {
                            mTvDesc.setVisibility(View.VISIBLE);
                        }
                    }
                }
            });

        }

        @Override
        public void uploadFailed() {

        }
    };


}
